package DMSXL._2024.Graph;

public class numIslands {
    public static void main(String[] args) {

    }
    public int numIslands(char[][] grid) {
        //对图进行遍历
        int result = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                //说明目前是陆地，则记录下来并且把周围全部淹没
                if(grid[i][j] == '1'){
                    result++;
                    dfs(grid,i,j);
                }
            }
        }
        return result;
    }
    //dfs实现淹没岛屿的过程
    public void dfs(char[][] grid, int i, int j){
        if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length ||  grid[i][j] == '0'){
            return;
        }
        grid[i][j] = '0';

        dfs(grid,i + 1,j);
        dfs(grid,i - 1,j);
        dfs(grid,i,j + 1);
        dfs(grid,i,j - 1);
    }
}
